from django_redis import get_redis_connection
from django.views import View
from django.http import HttpResponse, JsonResponse
import gvcode
import io

# Create your views here.
from ronglian_sms_sdk import SmsSDK


class ImageCodeView(View):

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        # 生成base64编码图片,默认为png格式
        # image, text = gvcode.base64()

        # 转为二进制图片发送
        image, text = gvcode.generate()
        # 创建一个字节流管道
        img_bytes = io.BytesIO()
        # 将图片数据存入字节流管道， format可以按照具体文件的格式填写
        image.save(img_bytes, format="PNG")
        # 从字节流管道中获取二进制
        image_bytes = img_bytes.getvalue()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应图片验证码
        return HttpResponse(image_bytes, content_type='image/jpeg')


from django import http
import random
import logging

logger = logging.getLogger('django')


class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # # 接收参数
        #
        # image_code_client = reqeust.GET.get('image_code')
        # uuid = reqeust.GET.get('image_code_id')
        #
        # # 校验参数
        # if not all([image_code_client, uuid]):
        #     return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'},
        #                             json_dumps_params={"ensure_ascii": False})
        #
        # # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # # 提取图形验证码
        # image_code_server = redis_conn.get('img_%s' % uuid)
        # if image_code_server is None:
        #     # 图形验证码过期或者不存在
        #     return JsonResponse({'code': 400, 'errmsg': '图形验证码失效'},
        #                             json_dumps_params={"ensure_ascii": False})
        # # 删除图形验证码，避免恶意测试图形验证码
        # try:
        #     redis_conn.delete('img_%s' % uuid)
        # except Exception as e:
        #     logger.error(e)
        # # 对比图形验证码
        # image_code_server = image_code_server.decode()  # bytes转字符串
        # if image_code_client.lower() != image_code_server.lower():  # 转小写后比较
        #     return JsonResponse({'code': 400, 'errmsg': '输入图形验证码有误'},
        #                             json_dumps_params={"ensure_ascii": False})

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'},
                                json_dumps_params={"ensure_ascii": False})

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        # 保存短信验证码

        # 创建Redis管道
        pl = redis_conn.pipeline()
        # 将Redis请求添加到队列
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        # 执行请求
        pl.execute()

        from celery_tasks.sms.tasks import celery_send_sms_code
        celery_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return JsonResponse({'code': 0, 'errmsg': '发送短信成功'},
                            json_dumps_params={"ensure_ascii": False})

    def post(self, request, mobile):
        sms_code = request.POST.get('sms_code')
        print(sms_code, mobile)
        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'},
                                json_dumps_params={"ensure_ascii": False})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code != sms_code_server.decode():
            print(sms_code_server.decode())
            print(sms_code)
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'},
                                json_dumps_params={"ensure_ascii": False})
        else:
            return JsonResponse({'code': 200},
                                json_dumps_params={"ensure_ascii": False})
